// 语言
import { createI18n } from 'vue-i18n/dist/vue-i18n.esm-browser.prod.js';

import zh from './lang/zh';
import en from './lang/en';

import { storage } from '@/utils/Storage';

export function getLanguage() {
  let lang = storage.get('language') || '';

  if (!lang || !(lang === 'zh' || lang === 'en')) {
    const navigatorLanguage = (
      navigator.language || (navigator as any).browserLanguage
    ).toLowerCase();

    lang = 'zh';

    if (navigatorLanguage) {
      switch (navigatorLanguage) {
        case 'zh-cn':
          lang = 'zh';
          break;
        case 'zh-tw':
          lang = 'zh';
          break;
        case 'en':
          lang = 'en';
          break;
        default:
          lang = 'zh';
      }

      storage.removeCookie('language');
    }
  }

  return lang;
}

export const messages = {
  en: {
    ...en,
  },
  zh: {
    ...zh,
  },
};

const i18n = createI18n({
  legacy: false,
  locale: getLanguage(),
  fallbackLocale: 'zh',
  messages,
});

export const { t, locale } = i18n.global;

export default i18n;
